﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;
using System.Threading;
using System.Windows;
using System.Diagnostics;
using System.Windows.Controls;
using System.ComponentModel;
using Ionic.Zip;

namespace UpdaterClass
{
    class Updater
    {
        private String _versionXmlAddress = @"http://rbkm.ru/userid/RobotLazarev/version.xml";
        private ListBox _logListBox;
        private ProgressBar _progressBar;
        private Button _button2;
        private Button _button1;
        private int _perSent = 0;

        public Version VersionNew;
        public String Path;
        public String UpdateLoadFilePath = "";
        
        public void Run ( )
        {
            GetVersion( );
        }

        private void GetVersion ( )
        {
            XmlDocument xmlDoc = new XmlDocument( );
            xmlDoc.Load( _versionXmlAddress );

            XmlNodeList version = xmlDoc.GetElementsByTagName( "version" );
            XmlNodeList path = xmlDoc.GetElementsByTagName( "path" );

            if ( version.Count == 1 && path.Count == 1 )
            {
                VersionNew = new Version(version.Item(0).InnerText);
                Path = path.Item( 0 ).InnerText;
            }
            else
            {
                VersionNew = null;
                Path = null;
            }
        }

        public void LoadZipFile ( ListBox RichTextBox_Log, ProgressBar progressBar1, Button button2, Button button1 )
        {
            try
            {
                _logListBox = RichTextBox_Log;
                _progressBar = progressBar1;
                _button2 = button2;
                _button1 = button1;
                WebClient client = new WebClient( );
                client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler( client_DownloadFileCompleted );
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler( client_DownloadProgressChanged );
                
                UpdateLoadFilePath = String.Format( "{4}\\RiskMan\\v{0}_{1}_{2}_{3}.zip", VersionNew.Major, VersionNew.Minor, VersionNew.Build, VersionNew.Revision, Environment.GetFolderPath( Environment.SpecialFolder.CommonDocuments ) );
                client.DownloadFileAsync(
                    new System.Uri( Path ),
                    UpdateLoadFilePath
                );
            }
            catch ( Exception ex )
            {
                _logListBox.Items.Add( ex.ToString( ) );
            }
        }

        private void client_DownloadFileCompleted ( object sender, AsyncCompletedEventArgs args )
        {
            if ( args.Error != null )
                _logListBox.Items.Add( "Ошибка: " + args.Error );
            else
            {
                _button1.Visibility = System.Windows.Visibility.Visible;
                _button2.IsEnabled = false;
                _logListBox.Items.Add( "Загрузка обновления завершена" );
            }
        }

        private void client_DownloadProgressChanged ( object sender, DownloadProgressChangedEventArgs args )
        {
            _progressBar.Value = args.ProgressPercentage;
        }

        public void InstallLoadedFile ( )
        {
            if ( ExtractZipFile( System.IO.Path.GetDirectoryName( Application.ResourceAssembly.Location ) + "\\" ) == true )
            {
                _logListBox.Items.Add( "Установка обновления завершена" );
                _button1.IsEnabled = false;
            }
        }

        private bool ExtractZipFile(string path)
        {
            try
            {
                using ( ZipFile zip = ZipFile.Read( UpdateLoadFilePath ) )
                {
                    foreach ( var e in zip )
                    {
                        e.Extract( path, ExtractExistingFileAction.OverwriteSilently );
                    }
                }
                return true;
            }
            catch ( Exception ex )
            {
                _logListBox.Items.Add( ex.ToString());
                return false;
            }
        }

    }
}